import 'package:flutter/material.dart';

mixin BasePageLifecycleStateMixin {
  void pageDidLoad();
  void pageDidAppear(bool isPush);
  void pageDidDisappear(bool isPop);
  void appEnterForeground();
  void appEnterBackground();
  void pageDidDispose();
}

final RouteObserver<PageRoute> pageLifecycleRouteObserver = RouteObserver<PageRoute>();

/// 页面生命周期监听基类
abstract class BasePageLifecycleState<T extends StatefulWidget> extends State<T>
    with WidgetsBindingObserver, RouteAware, BasePageLifecycleStateMixin {
  // 当前页面是否可见
  bool _isPageVisible = false;
  // 应用是否处于活动状态
  bool _isAppActive = true;
  String _pageName = 'BasePageLifecycleState';

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _pageName = context.widget.runtimeType.toString();
    pageDidLoad();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context) as PageRoute;
    pageLifecycleRouteObserver.subscribe(this, route);
  }

  @override
  void dispose() {
    pageLifecycleRouteObserver.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    pageDidDispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        _isAppActive = true;
        if (_isPageVisible) {
          appEnterForeground();
        }
        break;
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.paused:
        _isAppActive = false;
        if (_isPageVisible) {
          appEnterBackground();
        }
        break;
      case AppLifecycleState.detached:
        break;
      case AppLifecycleState.hidden:
        break;
    }
  }

  @override
  void didPush() {
    // 页面入栈
    _isPageVisible = true;
    pageDidAppear(true);
  }

  @override
  void didPopNext() {
    // 前一个页面出栈，当前页面可见
    _isPageVisible = true;
    if (_isAppActive) {
      pageDidAppear(false);
    }
  }

  @override
  void didPop() {
    // 当前页面出栈
    _isPageVisible = false;
    pageDidDisappear(true);
  }

  @override
  void didPushNext() {
    // 新页面入栈，当前页面被覆盖
    _isPageVisible = false;
    pageDidDisappear(false);
  }

  @override
  void pageDidLoad() {
    debugPrint("$_pageName->pageDidLoad");
  }

  @override
  void pageDidAppear(bool isPush) {
    debugPrint("$_pageName->pageDidAppear");
  }

  @override
  void pageDidDisappear(bool isPop) {
    debugPrint("$_pageName->pageDidDisappear");
  }

  @override
  void pageDidDispose() {
    debugPrint("$_pageName->pageDispose");
  }

  @override
  void appEnterForeground() {
    debugPrint("$_pageName->appEnterForeground");
  }

  @override
  void appEnterBackground() {
    debugPrint("$_pageName->appEnterBackground");
  }
}
